package com.youthfilmic.yuejian.weixin.pay;

import com.youthfilmic.yuejian.conn.WeixinConn;
import com.youthfilmic.yuejian.util.HttpUtil;
import com.youthfilmic.yuejian.util.MD5Util;
import com.youthfilmic.yuejian.util.XMLUtil;
import com.youthfilmic.yuejian.weixin.core.WeixinSignBean;
import net.sf.json.JSONObject;

import java.util.*;

/**
 * Created by youweixi on 15/10/7.
 */
public class WeixinPayAPI {

    /**
     * @title 通过为新的一些列规则获取sign
     * @instruction 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     * @param packageParams 排序过的参数
     * @author youweixi
     * @time 2015.7.12
     */
    public static String createSign(SortedMap<String, String> packageParams) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + WeixinConn.WEIXIN_PAY_KEY);
        return MD5Util.MD5Encode(sb.toString(), "UTF-8");
    }

    /**
     * 获取时间戳
     * */
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 验证xml是否来自官方，根据sign算法
     * */
    public static boolean verifyXML(String xml){
        SortedMap<String , String> map = XMLUtil.getSortMapFromXml(xml);
        if (map==null || !map.containsKey("sign")) return false;
        String sign = (String)map.get("sign");
        String result = createSign(map);
        return result.equalsIgnoreCase(sign);
    }

    public static void main(String[] args){
        //String test = "<xml><appid><![CDATA[wxbe7b69f6478c40db]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1251775201]]></mch_id><nonce_str><![CDATA[55d319f10cf210c332525a5f]]></nonce_str><openid><![CDATA[o-S6RtyRzuR51I0itCFqlEIXQ5FE]]></openid><out_trade_no><![CDATA[55d319f10cf210c332525a5e]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[3C4CAFFC87D5CB90B772831106BF9F8F]]></sign><time_end><![CDATA[20150818194146]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1001480423201508180650487545]]></transaction_id></xml>";

        System.out.println(orderQuery(13L).toString());
    }

    /**
     * 查询订单状态
     * @ref https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_2&index=4
     * */
    public static JSONObject orderQuery(Long applicationId){
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";
        SortedMap<String , String> map = new TreeMap<>();
        String id = null;
        if (applicationId < 10) id = "0" + String.valueOf(applicationId);
        else id = String.valueOf(applicationId);
        map.put("appid", WeixinConn.APP_ID);
        map.put("mch_id" , WeixinConn.WEIXIN_MCH_ID);
        map.put("out_trade_no" , id);
        String nonce = UUID.randomUUID().toString().replace("-", "");
        map.put("nonce_str", nonce);
        map.put("sign", createSign(map));
        return HttpUtil.httpRequestFromXml(url, "POST" , XMLUtil.getXMLFromMap("xml", map));
    }


}
